<?php
// 数据库连接测试工具
header('Content-Type: text/html; charset=utf-8');

echo "<h2>数据库连接测试</h2>";

// 常见的数据库配置
$configs = [
    [
        'name' => 'PHPStudy 默认配置 (密码: root)',
        'host' => 'localhost',
        'username' => 'root',
        'password' => 'root'
    ],
    [
        'name' => '无密码配置',
        'host' => 'localhost', 
        'username' => 'root',
        'password' => ''
    ]
];

$dbname = 'visitor_tracker';

foreach ($configs as $config) {
    echo "<h3>测试: {$config['name']}</h3>";
    
    try {
        $dsn = "mysql:host={$config['host']};charset=utf8mb4";
        $pdo = new PDO($dsn, $config['username'], $config['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ]);
        
        echo "<p style='color: green;'>✅ 连接成功！</p>";
        
        // 尝试创建数据库
        try {
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbname}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            echo "<p style='color: green;'>✅ 数据库创建成功！</p>";
            
            // 显示配置信息
            echo "<div style='background: #f0f8ff; padding: 10px; border-radius: 5px; margin: 10px 0;'>";
            echo "<strong>请在 db_config.php 中使用以下配置：</strong><br>";
            echo "<pre>";
            echo "\$db_config = [\n";
            echo "    'host' => '{$config['host']}',\n";
            echo "    'dbname' => '{$dbname}',\n";
            echo "    'username' => '{$config['username']}',\n";
            echo "    'password' => '{$config['password']}',\n";
            echo "    'charset' => 'utf8mb4'\n";
            echo "];";
            echo "</pre>";
            echo "</div>";
            
            break; // 找到可用配置，退出循环
            
        } catch (PDOException $e) {
            echo "<p style='color: orange;'>⚠️ 数据库创建失败: " . $e->getMessage() . "</p>";
        }
        
    } catch (PDOException $e) {
        echo "<p style='color: red;'>❌ 连接失败: " . $e->getMessage() . "</p>";
    }
    
    echo "<hr>";
}

echo "<h3>手动配置</h3>";
echo "<p>如果以上配置都不工作，请手动修改 <code>db_config.php</code> 文件中的数据库配置。</p>";
?>